<template>
  <el-dialog :destroy-on-close="true" :lock-scroll="false" :title="form_title" :visible.sync="visible"
             width="750px">
    <!--    form start   -->
    <el-form ref="product_form" :model="product_form" :rules="rules" label-width="82px">
      <el-form-item label="所属客户" prop="customer_name">
        <el-autocomplete v-model="product_form.customer_name" :fetch-suggestions="querySearchCustomer"
                         placeholder="请搜索所属客户"
                         value-key="name" @select="handleSelectCustomer">
          <template v-slot="{ item }">
            <div style="color: #333;"><b>{{ item ? item.name : '' }}</b></div>
            <div class="name" style="margin-top: -4px; display: flex;">
              电话: <span style="margin-right: 14px;">{{ item.user ? item.user.phone : '无' }}</span>
              编号: <span style="margin-right: 14px;">{{ item.customer_number }}</span>
              联系人: <span>{{ item.user ? item.user.name : '无联系人' }}</span>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="产品名称" prop="name">
        <el-input :maxlength="100" v-model="product_form.name" placeholder="请输入产品名称"/>
      </el-form-item>
      <el-form-item label="产品类型" prop="type_name">
        <el-autocomplete v-model="product_form.type_name" :fetch-suggestions="querySearchType"
                         placeholder="请搜索产品类型"
                         value-key="name" @select="selectProductItem"/>
      </el-form-item>
      <el-form-item label="服务网点:" prop="department_id">
        <el-select
          v-model="product_form.department_id"
          class="ele-block"
          clearable
          placeholder="请选择服务网点">
          <el-option
            v-for="(item, index) in deptLists"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="安装地址" prop="install_address">
        <el-input :maxlength="100" v-model="product_form.install_address" placeholder="请输入安装地址"/>
      </el-form-item>
      <el-form-item label="购买日期" prop="date_buy">
        <el-date-picker v-model="product_form.date_buy" class="c-picker" placeholder="选择购买日期" type="date"
                        value-format="yyyy-MM-dd"/>
      </el-form-item>
      <el-form-item label="验收日期" prop="date_check">
        <el-date-picker v-model="product_form.date_check" class="c-picker" placeholder="选择验收日期" type="date"
                        value-format="yyyy-MM-dd"/>
      </el-form-item>
      <el-form-item label="出厂报告">
        <template>
          <el-upload
            :file-list="fileList"
            :http-request="upload"
            :limit="1"
            :on-change="uploadHandleChange"
            :show-file-list="false"
            accept=".xls,.xlsx,.docx,application/msword,application/vnd.ms-excel,application/pdf"
            action="#"
            class="upload-demo"
            multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xls/xlsx/docx/pdf文件，且不超过10m</div>
          </el-upload>

          <span v-if="product_form.attachment" key="1" style="color: deepskyblue">
            {{ product_form.attachment }}
            <span style="cursor: pointer;color: black" @click="delAttachment">&nbsp;&nbsp;删除</span></span>
        </template>
      </el-form-item>
      <el-form-item label="保质期">
        <template>
          <el-radio-group v-model="radio" @change="selectType">
            <el-radio v-model="product_form.warranty_type" label="at">自动计算</el-radio>
            <el-radio v-model="product_form.warranty_type" label="mt">手动添加</el-radio>
          </el-radio-group>
        </template>
        <template>
          <div v-if="product_form.type_name && product_form.warranty_type === 'at'"
               class="p-3 bg-gray-100 mb-2 leading-normal">
            <div class="mb-1 text-black">计算规则</div>
            <div class="text-xs">
              质保期时长：{{ productType.warranty_cycle_count || '' }}
              {{ productType.warranty_start_unit || '' }}
            </div>
          </div>

          <div v-if="product_form.type_name || product_form.warranty_type === 'mt'">
            <el-date-picker v-model="product_form.warranty_start" class="c-picker" placeholder="质保开始日期"
                            size="small"
                            type="date" value-format="yyyy-MM-dd" @change="changeStartTime"/>
            <el-date-picker v-model="product_form.warranty_end" :disabled="product_form.warranty_type === 'at'"
                            :picker-options="product_form.endTimeOptions" placeholder="质保结束日期" size="small"
                            type="date"
                            value-format="yyyy-MM-dd"/>
            <div>质保状态: {{ expirationStatus }}</div>
          </div>
        </template>
        <el-alert v-if="product_form.warranty_type === 'at' && !product_form.type_name" :closable="false"
                  class="h-8 py-0" show-icon
                  title="未选择产品类型，无法进行自动计算。请选择&quot;产品类型&quot;或&quot;手动添加&quot;"
                  type="warning"/>
      </el-form-item>
    </el-form>
    <!--    form end     -->
    <div slot="footer">
      <el-button @click="handleCancel()">取消</el-button>
      <el-button :loading="loading" type="primary" @click="handleSave('product_form')">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import Moment from "moment/moment";

export default {
  name: "product-form",
  data() {
    return {
      type: null,
      visible: false,
      rules: {
        name: [
          {required: true, message: "请输入产品名称", trigger: "blur"}
        ],
        customer_name: [{required: true, message: "请搜索所属客户", trigger: "change"}],
        type_name: [{required: true, message: "请搜索产品类型", trigger: "change"}],
        department_id: [{required: true, message: "请选择服务网点", trigger: "change"}],
        install_address: [
          {required: true, message: "请输入详细地址", trigger: "blur"}
        ],
        date_buy: [
          {required: true, message: "请选择购买日期", trigger: "blur"}
        ],
        date_check: [
          {required: true, message: "请选择验收日期", trigger: "blur"}
        ],
        address: [
          {required: true, message: "请输入详细地址", trigger: "blur"}
        ],
      },
      product_form: {
        customer: {},
        qrcode: {},
        type:{},
      },
      form_title: "",
      loading: false,
      deptLists: [],
      fileList: [],
      //选择文件保质期方式
      radio: "at",
      productType: {},
    }
  },
  mounted() {
    /**获取服务网点*/
    this.getDeptList();
  },
  computed: {
    expirationStatus() {
      if (!this.product_form.warranty_start) {
        return '请选择日期';
      }
      // this.product_form.warranty_end 小于当前时间，为保外
      if (this.product_form.warranty_end < Moment().format('YYYY-MM-DD')) {
        return '保外';
      } else {
        return '保内';
      }
    }
  },
  methods: {
    /**
     * @param type 弹窗类型
     * @param form 表单数据（建议后期优化为从后端获取数据）
     */
    showDialog(type, form) {
      this.visible = true;
      this.type = type;
      type === "add" ? this.product_form = {} : this.product_form = {
        ...form,
        customer_name: form.customer?.name || null,
        type_name:form.type?.name||null
      }
      this.product_form.warranty_type = "at"
      this.form_title = (type === "add" ? "添加产品" : "修改产品");
    },
    /** 保存事件 **/
    handleSave(val) {
      this.$refs[val].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.type === "add" ? this.addProduct(this.product_form) : this.editProduct(this.product_form)
      });
    },
    // 新增产品
    addProduct(params) {
      this.$http.post('/products', params).then(res => {
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.handleCancel();
          this.$emit("reload")
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.loading = false;
        this.$message.error(e.message);
      });
    },
    // 编辑产品
    editProduct(params) {
      this.$http.put('products/' + params.id, params).then(res => {
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.handleCancel();
          this.$emit("reload")
        }
      }).catch(e => {
        this.loading = false;
        this.$message.error(e.message);
      });
    },
    /** 取消事件 **/
    handleCancel() {
      this.visible = false;
      this.$refs['product_form'].resetFields();
    },
    /**--- 逻辑处理 start ---**/
    querySearchCustomer(query, cb) {
      this.$http.get("customers", {
        params: {
          keyword: query,
          page: 1,
          limit: 10
        }
      }).then((res) => {
        cb(res.data.data);
      });
    },
    handleSelectCustomer(item) {
      this.product_form.customer_id = item.id;
    },
    querySearchType(query, cb) {
      this.$http.get("product_types", {
        params: {
          name: query,
          page: 1,
          limit: 10
        }
      }).then((res) => {
        cb(res.data.data);
      });
    },
    selectProductItem(item) {
      this.productType = item
      this.product_form.type_id = item.id;
    },
    upload(file) {
      const formData = new FormData();
      formData.append("attachment", file.file);
      this.$http.post("files/filesStore", formData).then((res) => {
        console.log(111,res.data.data.path)
        this.product_form.attachment = res.data.data.path;
        //聚焦刷新
        this.$forceUpdate()
      });
    },
    uploadHandleChange(file) {
      if (file.status === "error") {
        this.$message.error("上传失败");
      }
    },
    //获取deptList
    getDeptList() {
      const loading = this.$loading({lock: true});
      this.$http.get('/dept/index').then(res => {
        loading.close();
        if (res.data.code === 0) {
          this.deptLists = res.data.data.filter(item => {
            if (item.type === 3) {
              return item
            }
          })
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        loading.close();
        this.$message.error(e.message);
      });
    },
    delAttachment() {
      this.fileList = []
      this.product_form.attachment = ''
    },
    selectType(val) {
      this.product_form.warranty_type = val
      this.$forceUpdate()
    },
    changeStartTime() {
      // 当 product_form.warranty_type 为 mt 自动计算时，保质期结束时间自动计算 + 质保期时长
      if (this.product_form.warranty_type !== 'mt') {
        this.product_form.warranty_end = Moment(this.product_form.warranty_start).add(this.productType.warranty_cycle_count, this.productType.warranty_start_unit).format('YYYY-MM-DD');
        this.$forceUpdate()
      }
    },
    /**--- 逻辑处理 end ---**/
  }
}
</script>

<style scoped>

</style>
